package xj.toolkit.netty.handler.codec.http.reactor;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import xj.toolkit.base.Sender;
import xj.toolkit.netty.handler.codec.http.request.HttpRequestExt;
import xj.toolkit.netty.handler.codec.http.response.ConstantResponse;
import xj.toolkit.netty.transport.TransportUtils;
import xj.toolkit.netty.util.NettyConstants;

/**
 * @author hp
 * 
 */
public class SendbackResponseReactor implements HttpReactor {

	private static final Logger logger = LoggerFactory.getLogger(SendbackResponseReactor.class);

	private HttpReactor nextReactor = null;

	public HttpReactor getNextReactor() {
		return nextReactor;
	}

	public void setNextReactor(HttpReactor nextReactor) {
		this.nextReactor = nextReactor;
	}

	@Override
	public void onHttpRequest(FullHttpRequest request) {
		Assert.isInstanceOf(HttpRequestExt.class, request, "request must be type of HttpRequestExt");
		HttpRequestExt requestExt = (HttpRequestExt) request;
		HttpResponse resp = ConstantResponse.getOkResponse();
		String uuid = request.headers().get(NettyConstants.HEADER_UUID);
		if (uuid != null) {
			resp.headers().set(NettyConstants.HEADER_UUID, uuid);
		}
		Sender sender = TransportUtils.getSenderOf(requestExt);
		if (sender == null) {
			logger.error("Cannot get sender of FullHttpRequest[{}].", request);
		} else {
			sender.send(resp);
		}
		if (null != this.nextReactor) {
			nextReactor.onHttpRequest(request);
		}
	}

}
